package com.example.mybatisplusdemo.web.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.IUserService;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 用户前端控制器
 * </p>
 *
 * @author yangpengfei
 * @since 2025/01/27
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     * 
     * 业务逻辑说明：
     * 1. 验证用户名和密码
     * 2. 登录成功后将用户信息保存到session
     * 3. 返回用户详细信息
     * 
     * @param loginRequest 登录请求参数
     * @return JsonResponse<Map<String, Object>> 登录结果
     */
    @PostMapping("/login")
    public JsonResponse<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String loginName = loginRequest.get("loginName");
            String password = loginRequest.get("password");
            
            if (loginName == null || loginName.trim().isEmpty()) {
                return JsonResponse.failure("用户名不能为空");
            }
            
            if (password == null || password.trim().isEmpty()) {
                return JsonResponse.failure("密码不能为空");
            }
            
            // 查询用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", loginName)
                       .eq("password", password);
            User user = userService.getOne(queryWrapper);
            
            if (user == null) {
                return JsonResponse.failure("用户名或密码错误");
            }
            
            // 保存用户信息到session
            SessionUtils.saveCurrentUserInfo(user);
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("id", user.getId());
            result.put("loginName", user.getUsername());
            result.put("realName", user.getUsername());
            result.put("email", user.getEmail());
            result.put("phone", user.getPhone());
            result.put("remark", user.getPhone()); // 使用phone作为备注信息
            
            log.info("用户登录成功，用户名: {}", loginName);
            return JsonResponse.success(result, "登录成功");
            
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return JsonResponse.failure("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     * 
     * 业务逻辑说明：
     * 1. 从session中获取当前用户信息
     * 2. 返回用户详细信息
     * 
     * @return JsonResponse<Map<String, Object>> 用户信息
     */
    @GetMapping("/getInfo")
    public JsonResponse<Object> getCurrentUserInfo() {
        try {
            User currentUser = SessionUtils.getCurrentUserInfo();
            
            if (currentUser == null) {
                return JsonResponse.failure("用户未登录").setCode(401);
            }
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("id", currentUser.getId());
            result.put("loginName", currentUser.getUsername());
            result.put("realName", currentUser.getUsername());
            result.put("email", currentUser.getEmail());
            result.put("phone", currentUser.getPhone());
            result.put("remark", currentUser.getPhone()); // 使用phone作为备注信息
            
            return JsonResponse.success(result, "获取用户信息成功");
            
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return JsonResponse.failure("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<User> getById(@PathVariable("id") Long id)throws Exception {
        User user = userService.getById(id);
        return JsonResponse.success(user);
    }
}

